﻿using MergerProject;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Serialization;

namespace MergeToolSample
{
    public partial class CustomServers : Form
    {
        IMerger merger;
        public CustomServers(IMerger merger)
        {
            this.merger = merger;
            InitializeComponent();
        }

        private void CustomServers_Load(object sender, EventArgs e)
        {
            GetServersFromXML();
            if (merger.myCustomServerList != null && merger.myCustomServerList.serverList!=null)
            { 
            foreach (var item in merger.myCustomServerList.serverList)
            {
                listBox1.Items.Add(item.TfsUrl);
            }
            }
        }

        public void GetServersFromXML()
        {
            // Create an instance of the XmlSerializer specifying type and namespace.
            XmlSerializer serializer = new
            XmlSerializer(typeof(TFSServerList));

            // A FileStream is needed to read the XML document.
            FileStream fs = new FileStream("Servers.xml", FileMode.Open);
            StreamReader rd = new StreamReader(fs);
            string data = rd.ReadToEnd();
            StringReader reader = new StringReader(data);
            // Use the Deserialize method to restore the object's state.

            merger.myCustomServerList = (TFSServerList)serializer.Deserialize(reader);
            fs.Close();
            rd.Close();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (listBox1.SelectedIndex>=0)
            {
            merger.myCustomServerList.serverList.RemoveAt(listBox1.SelectedIndex);
            listBox1.Items.RemoveAt(listBox1.SelectedIndex);
            SerializeObject();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(textBox1.Text))
            {
                merger.myCustomServerList.serverList.Add(new TFSServer { TfsUrl = textBox1.Text });
                listBox1.Items.Add(textBox1.Text);
                textBox1.Text = string.Empty;
                SerializeObject();
            }
             
        }


        public  void SerializeObject()
        {
            XmlSerializer serializer =
            new XmlSerializer(typeof(TFSServerList));
           // Writing the document requires a TextWriter.
            TextWriter writer = new StreamWriter("Servers.xml");
            // Serialize the object, and close the TextWriter.
            serializer.Serialize(writer, merger.myCustomServerList);
            writer.Close();
        }
    }
}
